<template>
  <div class="add-task-tem">
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :visible.sync="addTaskData.isShow" :title="$t('qualityCheck.extractTaskTemplate')" style="min-width:800px;" @close="addTaskDataClose">
      <el-form :inline="true" label-position="right" ref="form" :model="form" :rules="rules">
        <el-form-item :label="$t('qualityCheck.taskName')" prop="TASK_NAME">
          <el-input v-model.trim="form.TASK_NAME" size="mini" :maxlength=10 :placeholder="$t('qualityCheck.theMostChart')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('qualityCheck.qualityTemplate')" prop="TASK_TEMPLATE" class="radio-template">
          <el-radio-group class="radio-group" v-model.trim="form.TASK_TEMPLATE" v-if="addTaskData.qualityCheckTemplates.length!==0">
            <el-radio size="mini"
                      v-if="item.QUALITY_TYPE !== 'qualityWebchat'"
                      v-for="(item, index) in addTaskData.qualityCheckTemplates"
                      :key="index"
                      :label="item._id">
              {{item.name}}
              <!--{{item.QUALITY_TYPE === 'qualityWebchat' ? item.name + '[在线咨询]' : item.name + '[通话]'}}-->
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('qualityCheck.extractRules')">
          <el-radio-group v-model.trim="selectRule" @change="changeChouQuRadio">
            <div class="chouqu-guize">
              <el-radio class="radio" name="selectRule" label="num" size="mini">{{$t('qualityCheck.numArticles')}}</el-radio>
              <el-select style="width:100px;" size="mini" v-model.trim="cacheForm.sampleNum" :disabled="chouquState === 'percent'">
                <el-option :label="$t('qualityCheck.numPerCapita')" value="per_num"></el-option>
                <el-option :label="$t('qualityCheck.wholeNumArticles')" value="entirety_num"></el-option>
              </el-select>
              <el-form-item class="count"  prop="count">
                <el-input size="mini" style="width:60px;" v-model.trim="form.count" :disabled="chouquState === 'percent'"></el-input>
              </el-form-item>
            </div>
            <div class="chouqu-guize">
              <el-radio class="radio"  name="selectRule" label="percent" size="mini">{{$t('qualityCheck.percentage')}}</el-radio>
              <el-select style="width:100px;" size="mini" v-model="cacheForm.samplePercent" :disabled="chouquState === 'num'">
                <el-option :label="$t('qualityCheck.perCapitaPercentage')" value="per_percent"></el-option>
                <el-option :label="$t('qualityCheck.wholeCapitaPercentage')" value="entirety_percent"></el-option>
              </el-select>
              <el-form-item class="percent" prop="percent">
                <el-input :disabled="chouquState === 'num'" size="mini" style="width:100px;" v-model.trim="form.percent">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('public.callTime')" prop="callTime">
          <el-date-picker size="mini"
                          :id="['e1','e2']"
                          v-model.trim="cacheForm.callTime"
                          type="datetimerange"
                          :picker-options="pickerOptions2"
                          :placeholder="$t('public.timeRanges')"
                          :editable="false"
                          align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('call.callType')" prop="CONNECT_TYPE">
          <el-select v-model="cacheForm.CONNECT_TYPE" multiple :placeholder="$t('call.callTypeSearch')" size="mini">
            <el-option
              v-for="(item, index) in callTypeList"
              :key="index"
              :label="item.code_name"
              :value="item.code_value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('public.queues')">
          <el-select size="mini" v-model.trim="cacheForm.QUEUE" multiple filterable :placeholder="$t('qualityCheck.skillGroupSearch')">
            <el-option
              v-for="(item, index) in callQueueList"
              :key="index"
              :label="item.DisplayName"
              :value="item.Exten">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('qualityCheck.checkWorker')" prop="QA_SPECIALIST">
          <!-- <el-select size="mini" v-model.trim="form.QA_SPECIALIST" filterable :placeholder="$t('public.pickAgentTip')">
            <el-option
              v-for="(item, index) in callAgentList"
              :key="index"
              :label="item.displayName + '[' + item.exten + ']'"
              :value="item._id">
            </el-option>
          </el-select> -->
          <m7Select class="el-select" filterable :placeholder="$t('public.pickAgentTip')" :options="selectAgents" v-model="form.QA_SPECIALIST"></m7Select>
        </el-form-item>
        <el-form-item :label="$t('public.satisfaction')" prop="INVESTIGATE">
          <el-select size="mini" v-model.trim="form.INVESTIGATE" filterable :placeholder="$t('webchat.webchatAll')">
            <el-option value="" :label="'--'+$t('webchat.webchatAll')+'--'"></el-option>
            <el-option value="unevaluated" :label="'--'+$t('public.unevaluated')+'--'"></el-option>
            <el-option
              v-for="(item, index) in satisfactionList"
              :key="index"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('call.callTime')">
          <el-col :span="11">
            <el-form-item prop="CALL_TIME_LENGTH_BEGIN">
              <el-input
                style="width:100px;"
                size="mini"
                placeholder=""
                :maxlength=10
                v-model="form.CALL_TIME_LENGTH_BEGIN">
                <template slot="append">{{$t('public.seconds')}}</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2"><span style="margin-top: 6px;display:inline-block;font-size:12px;">{{$t('public.to')}}</span></el-col>
          <el-col :span="11">
            <el-form-item prop="CALL_TIME_LENGTH_END">
              <el-input
                style="width:100px;"
                size="mini"
                placeholder=""
                :maxlength=10
                v-model="form.CALL_TIME_LENGTH_END">
                <template slot="append">{{$t('public.seconds')}}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('public.callLabel')">
          <label-cascader @labelSelect="labelSelect" :resetSelect="resetSelect" :needType="true"></label-cascader>
        </el-form-item>
        <el-form-item v-show="callAgentShow" :label="$t('qualityCheck.callAgent')+':'">
          <!-- <el-select size="mini" v-model.trim="cacheForm.selectedAgentList" multiple filterable :placeholder="'--'+$t('webchat.webchatAll')+'--'">
            <el-option :label="'--'+$t('webchat.webchatAll')+'--'" value=""></el-option>
            <el-option
              v-for="(item, index) in callAgentList"
              :key="index"
              :label="item.displayName + '[' + item.exten + ']'"
              :value="item._id">
            </el-option>
          </el-select> -->
          <m7Select class="el-select" multiple filterable :placeholder="$t('qualityCheck.skillGroupSearch')" :options="selectAgents" v-model="cacheForm.selectedAgentList"></m7Select>
          <el-checkbox style="margin-left: 20px;"  v-model="form.includeSubordinate" :label="$t('public.includeUnderAgent')" name="type"></el-checkbox>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click="resetForm">{{$t('public.reset')}}</el-button>
          <el-button class="primary_btn" type="primary" @click="onSubmit">{{$t('qualityCheck.createTaskAndRxtract')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import LabelCascader from '@/components/public-modules/phone-bar/LabelCascader.vue'
  import {deepClone, getDateTime, m7Language, isHasFunc} from '@/utils/m7Utils'
  import {checkform} from '@/utils/validate.js'
  import * as globalTypes from '@/store/mutation-types'
  export default {
    name: 'addTaskTem',
    data () {
      let validate1 = (rule, value, callback) => {
        if (value !== '') {
          let match = checkform(value, 'Number3')
          if (match) {
            callback(new Error(this.$t('qualityCheck.pleaseEnterNum')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
//      let validateCallLength = (rule, value, callback) => {
//        let item = self.callForm
//        if (item.CALL_TIME_LENGTH_BEGIN !== '' && item.CALL_TIME_LENGTH_END !== '') {
//          if (parseInt(item.CALL_TIME_LENGTH_END) < item.CALL_TIME_LENGTH_BEGIN) {
//            callback(new Error(this.$t('qualityCheck.PleaseEnterTheCorrectCallDurationRrange')))
//          } else {
//            callback()
//          }
//        } else {
//          callback()
//        }
//      }
      return {
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        chouquState: 'num',
        selectRule: 'num',
        taskTemVal: 0,
        labelType: 'single',
        form: {
          TASK_NAME: '',
          TASK_TEMPLATE: '',                 // 质检模板
          BEGIN_TIME: '',
          END_TIME: '',
          QA_SPECIALIST: '',                 // 质检员
//          selectedAgents: '',
          selectedAgentList: '',             // 通话座席
          includeSubordinate: false,         // 是否包含下级
          CALL_TIME_LENGTH_BEGIN: '',        // 通话时长
          CALL_TIME_LENGTH_END: '',
          multiLabel: [],
          singleLabel: '',                   // 录音标签
          INVESTIGATE: '',                   // 满意度
          sample_selection_rule: '',         // 抽取规则
          count: 10,
          percent: 10,
          QUEUE: '',                         // 技能组
          CONNECT_TYPE: '',                   // 呼叫类型
          page: 1
        },
        cacheForm: {
          sampleNum: 'per_num',
          samplePercent: 'per_percent',
          callTime: [],
          QUEUE: [],
          CONNECT_TYPE: [],
          selectedAgentList: []
        },
        callTypeList: [],                   // 呼叫类型
        callAgentList: [],                  // 质检专员
        callQueueList: [],                  // 技能组
        satisfactionList: [],               // 满意度
        qualityTasks: [],               // 任务模板
        callAgentShow: false,            // 是否显示座席信息
        resetSelect: false,
        rules: {
          count: [
            {validator: validate1, trigger: 'blur'}
          ],
          percent: [
            {validator: validate1, trigger: 'blur'}
          ],
          CALL_TIME_LENGTH_BEGIN: [
            {validator: validate1, trigger: 'blur'}
          ],
          CALL_TIME_LENGTH_END: [
            {validator: validate1, trigger: 'blur'}
          ]
        }
      }
    },
    props: {
      addTaskData: {
        type: Object,
        default: function () {
          return {
            isShow: false
          }
        }
      }
    },
    computed: {
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          let agentList = this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
          return agentList
        }
        return this.callAgentList
      }
    },
    watch: {
      cacheForm: {
        deep: true,
        handler (newV) {
          let cloneForm = deepClone(newV)
          this.handleForm(cloneForm)
        }
      },
      'addTaskData.isShow': 'resetForm'
    },
    methods: {
      changeChouQuRadio (value) {
        this.chouquState = value
      },
      handleForm (data) {
        if (data.callTime.length && data.callTime[0] !== null) {
          this.form.BEGIN_TIME = getDateTime(data.callTime[0])
        }
        if (data.callTime.length && data.callTime[1] !== null) {
          this.form.END_TIME = getDateTime(data.callTime[1])
        }
        if (this.chouquState === 'num') {
          this.form.sample_selection_rule = data.sampleNum
        } else if (this.chouquState === 'percent') {
          this.form.sample_selection_rule = data.samplePercent
        }
        if (data.QUEUE.length) {
          this.form.QUEUE = data.QUEUE.join(',')
        } else {
          this.form.QUEUE = ''
        }
        if (data.CONNECT_TYPE.length) {
          this.form.CONNECT_TYPE = data.CONNECT_TYPE.join(',')
        } else {
          this.form.CONNECT_TYPE = ''
        }
        if (data.selectedAgentList.length) {
          this.form.selectedAgentList = data.selectedAgentList.join(',')
        } else {
          this.form.selectedAgentList = ''
        }
      },
      renderCallCache () {
        this.$store.dispatch('getCache', {type: 'qualityTasks'}).then(() => {  // 呼叫类型
          this.qualityTasks = this.$getCache('qualityTasks')
        })
        let self = this
        this.$store.dispatch('getCache', {type: 'callType'}).then((res) => {  // 呼叫类型
          let callTypeListData = deepClone(res)
          callTypeListData = callTypeListData.filter(item => {
            item.code_name = m7Language('globalChineseKey.' + item.code_name, null, true) || item.code_name
            return item
          })
          self.callTypeList = callTypeListData
        })
        this.$store.dispatch('getCache', {type: 'agents'}).then((res) => { // 质检员
          res.forEach((agent) => {
            self.callAgentList.push({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id })
          })
        })
        this.$store.dispatch('getCache', {type: 'queues'}).then((res) => { // 技能组
          self.callQueueList = res
        })
        this.$store.dispatch('getCache', {type: 'options'}).then((res) => { // 满意度
          let _dics = []
          for (let i = 0; i < res.length; i++) {
            let obj = res[i]
            if (obj.name && obj.name === '满意度调查选项') {
              _dics = obj.options || []
              break
            }
          }
          let satisfactionList = []
          for (var n = 0; n < _dics.length; n++) {
            if (_dics[n] && _dics[n].name && _dics[n].options[0]) {
              satisfactionList.push({name: _dics[n].name, value: _dics[n].options[0].name})
            }
          }
          self.satisfactionList = satisfactionList
        })
        let newArr = []
        this.addTaskData.qualityCheckTemplates.forEach((item, index) => {
          if (item.QUALITY_TYPE !== 'qualityWebchat') {
            newArr.push(item)
          }
        })
        if (newArr.length) {
          this.form.TASK_TEMPLATE = newArr[0]._id
        }
      },
      onSubmit () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitForm()
          } else {
            this.$message.error(this.$t('qualityCheck.fillCorrectInfo'))
            return false
          }
        })
      },
      submitForm () {
        let data = deepClone(this.form)
        if (!data.TASK_NAME || data.TASK_NAME === '') {
          this.$message.error(this.$t('qualityCheck.fillQualityInspectionTask'))
          return
        }
        if (!data.TASK_TEMPLATE || data.TASK_NAME === '') {
          this.$message.error(this.$t('qualityCheck.chooseQualityTempl'))
          return
        }
        if (data.CALL_TIME_LENGTH_BEGIN && data.CALL_TIME_LENGTH_END) {
          let arraySta = parseInt(data.CALL_TIME_LENGTH_BEGIN)
          let arrayEnd = parseInt(data.CALL_TIME_LENGTH_END)
          if (arrayEnd <= arraySta) {
            this.$message.error(this.$t('qualityCheck.PleaseEnterTheCorrectCallDurationRrange'))
            return
          }
        } else if (data.CALL_TIME_LENGTH_BEGIN && data.CALL_TIME_LENGTH_END === '') {
          this.$message.error(this.$t('qualityCheck.PleaseEnterTheCorrectCallDurationRrange'))
          return
        }
        if (this.chouquState === 'num') {
          if (!parseInt(data.count) || data.count === '') {
            this.$message.error(this.$t('qualityCheck.numOfqualityRecords'))
            return
          }
          if (parseInt(data.count) === 0) {
            this.$message.error(this.$t('qualityCheck.theNumberOfQualityRecordsOne'))
            return
          }
          if (parseInt(data.count) > 1000) {
            this.$message.error(this.$t('qualityCheck.theNumberOfQualityRecordsThousand'))
            return
          }
          data.sample_selection_rule = this.cacheForm.sampleNum
          delete data.percent
        } else if (this.chouquState === 'percent') {
          if (!parseInt(data.percent) || data.percent === '') {
            this.$message.error(this.$t('qualityCheck.randomlyqualityRecordspercentage'))
            return
          }
          if (parseInt(data.percent) === 0) {
            this.$message.error(this.$t('qualityCheck.percentageRange'))
            return
          }
          if (parseInt(data.percent) > 100) {
            this.$message.error(this.$t('qualityCheck.percentageRange'))
            return
          }
          data.percent = data.percent + '%'
          data.sample_selection_rule = this.cacheForm.samplePercent
          delete data.count
        }
        if (!data.QA_SPECIALIST || data.QA_SPECIALIST === '' || data.QA_SPECIALIST === 'serachInputNoresult') {
          this.$message.error(this.$t('qualityCheck.fillNameOfQualityInspector'))
          return
        }
        this.$store.dispatch('addQualityTaskTemplate', data).then((res) => {
          if (!res.success) {
            if (res.message) {
              if (res.message === 'QualityNumRepeat') {
                this.$message.error(this.$t('qualityCheck.qualityInspectionTask'))
              } else {
                this.$message.error(res.message)
              }
              return
            }
          } else {
            if (res.condition && this.qualityTasks.indexOf(res.condition) === -1) {
              this.$store.commit(globalTypes.PUSH_TASK_TEM, res.condition)
            }
            if (res.count === 0) {
              this.$message.error(this.$t('qualityCheck.noEligibleCallRecords'))
              this.addTaskData.isShow = false
            }
            let selectId = ''
            if (res.selectedId) {
              selectId = res.selectedId
            }
            this.$emit('addTaskTem', selectId)
            this.addTaskData.isShow = false
          }
        })
      },
      queryRecordCallListenLog (_id, page) {
        this.currentId = _id
        this.title = this.$t('qualityCheck.callQualityLookLog')
        this.listenpp = this.$t('qualityCheck.checkPeople')
        this.listenTime = this.$t('qualityCheck.checkTime1')
        this.$store.dispatch('queryRecordCallListenLog', {'CALL_SHEET_ID': _id, 'page': page, 'pageSize': 10}).then(() => {
          this.recordList = this.$store.state.qualityCheck.recordList.list
          this.countRecord = this.$store.state.qualityCheck.recordList.count
          this.totalPageRecord = Math.ceil(this.$store.state.qualityCheck.recordList.count / 10) || 0
          this.isShow = true
        })
      },
      labelSelect (data) { // 子组件外抛出来的表单
        this.resetSelect = false
        if (data.type === 'single') {
          this.labelType = 'single'
          delete this.form.multiLabel
          this.form.singleLabel = data.arr[0] || ''
        } else {
          this.labelType = 'multi'
          this.form.multiLabel = data.arr && data.arr[0] ? data.arr : []
          delete this.form.singleLabel
        }
      },
      resetForm () {
        if (this.$refs['form']) {
          this.$refs['form'].resetFields()
          this.resetSelect = true
          this.selectRule = 'num'
          this.chouquState = 'num'
          this.form.includeSubordinate = false
          if (this.labelType === 'single') {
            this.form.singleLabel = ''
          } else {
            this.form.multiLabel = []
          }
          this.form.count = 10
          this.form.percent = 10
          this.cacheForm.sampleNum = 'per_num'
          this.cacheForm.samplePercent = 'per_percent'
          this.cacheForm.callTime = []
          this.cacheForm.QUEUE = []
          this.cacheForm.CONNECT_TYPE = []
          this.cacheForm.selectedAgentList = []
        }
      },
      addTaskDataClose () {
        this.resetForm()
      }
    },
    components: {
      LabelCascader
    },
    beforeMount () {
      this.renderCallCache()
      if (isHasFunc('func_call_quality_agent', this.$store.state.session.user)) {
        this.callAgentShow = true
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .add-task-tem
    .el-select
      width 200px
    .el-dialog--small
      min-width 800px
    .line
      margin-bottom 16px
    .temp-name
      width 140px
    .chouqu-guize
      display inline-block
    .count
      margin -6px 0 0 10px
    .percent
      margin -6px 0 0 10px
    .radio
      margin 0 10px
    .radio-group
      /*margin-left 90px*/
      /*margin-top -25px*/
      .el-radio
        margin 0 20px 0 0
  .select-wrap
    width 450px
    display block
    float left
  .radio-template
    display block
</style>
